package Connection;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author murcrayw6785
 */
public class Connection {

    private PrintWriter out;
    private BufferedReader in;
    private Socket socket;
    private Scanner scan;
    private String name;

    public Connection(Socket socket, String name) {
        this.socket = socket;
        this.name = name;
    }

    public void connect() throws IOException {
        out = new PrintWriter(socket.getOutputStream(), true);
        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        (new RecieveMessagesThread()).start();
        (new SendMessagesThread()).start();
    }

    private void sendMessages() {
        String outputLine;
        scan = new Scanner(System.in);
        System.out.println("Enter a message then hit enter:");
        do {
            outputLine = scan.nextLine();
            if (socket.isClosed()) {
                break;
            }
            out.println(outputLine);
        } while (!outputLine.equalsIgnoreCase("BYE"));
        try {
            scan.close();
            out.close();
            in.close();

            if (!socket.isClosed()) {
                socket.close();
            }

        } catch (IOException ioe) {
            System.exit(55);
        }
    }

    private void recieveMessages() {
        try {
            String inputLine;

            while ((inputLine = in.readLine()) != null) {
                System.out.println(name.toUpperCase() + "SAID: " + inputLine);
                if (inputLine.equalsIgnoreCase("BYE")) {
                    System.out.println("Connection closed by " + name.toUpperCase() + ". Type enter to exit.");
                    break;
                }
            }

            out.close();
            in.close();
            if (!socket.isClosed()) {
                socket.close();
            }

        } catch (IOException ioe) {
            System.out.println("Connection closed.");
        }
    }

    private class RecieveMessagesThread extends Thread {

        public void run() {
            recieveMessages();
        }
    }

    private class SendMessagesThread extends Thread {

        public void run() {
            sendMessages();
        }
    }
}
